<template>
	<view class="adup-jybz page-bg">
		<view class="fm-title">
			<view class="title"><label class="line-icon" :style="{'background': '#00c3c3'}"></label>加油报账</view>
			<u-button :loading="sb.load" type="success" @click="submitFm">
				<u-icon v-if="!sb.load" name="edit-pen-fill" color="#fff"
					:custom-style="{'margin-right': '10rpx'}"></u-icon>
				提交修改
			</u-button>
		</view>

		<u-form :model="fm" ref="bzfm" v-if="fm">
			<view class="my-fm">
				<view class="f-item no-box">
					<u-form-item>
						<view class="i-row">
							<view class="r-title">公里数</view>
							<view class="r-con">
								<u-input v-model="fm.currKm" :type="'digit'" :maxlength="8" :input-align="'right'"
									:clearable="false" :custom-style="{'color': '#00C3CE'}"
									placeholder="请输入车辆当前公里数" /><label class="i-r-text">公里</label>
							</view>
						</view>
					</u-form-item>

					<u-form-item>
						<view class="i-row">
							<view class="r-title">加油方式</view>
							<view class="r-con">
								<MySelect :title="'加油方式'" :name="'jyWay'" :list="jyWayList" :defval="fm.jyWay"
									@seledItem="mySeledMd"></MySelect>
							</view>
						</view>
					</u-form-item>

					<template>
						<u-form-item>
							<view class="i-row">
								<view class="r-title">加油金额</view>
								<view class="r-con">
									<u-input v-model="fm.jyMoney" :type="'digit'" :maxlength="6" :input-align="'right'"
										:clearable="false" :custom-style="{'color': '#00C3CE'}"
										:placeholder="'请输入加油金额'" /><label class="i-r-text">元</label>
								</view>
							</view>
						</u-form-item>
					</template>
					<u-form-item>
						<view class="i-row">
							<view class="r-title">加油数量</view>
							<view class="r-con">
								<u-input v-model="fm.jyCount" :type="'digit'" :maxlength="6" :input-align="'right'"
									:clearable="false" :custom-style="{'color': '#00C3CE'}"
									:placeholder="'请输入加油数量'" /><label class="i-r-text">升</label>
							</view>
						</view>
					</u-form-item>

					<template v-if="fm.jyWay.val != 'XJ_JY'">
						<u-form-item>
							<view class="i-row">
								<view class="r-title">加油站</view>
								<view class="r-con">
									<MySelect :title="'加油站'" :name="'jyStation'" :list="jyStationList"
										:defval="fm.jyStation" @seledItem="mySeledMd"></MySelect>
								</view>
							</view>
						</u-form-item>




					</template>

					<u-form-item>
						<view class="i-row">
							<view class="r-title">加油日期</view>
							<view class="r-con">
								<MyDateTime :name="'jyDate'" :showType="1" :datePlaceholder="'加油日期'"
									:dateTime="fm.jyDate" @myClick="setDateTime"></MyDateTime>
							</view>
						</view>
					</u-form-item>

					<u-form-item>
						<view class="i-row-textarea">
							<view class="r-title">备注</view>
							<view class="r-con">
								<u-input v-model="fm.jyRemark" :type="'textarea'" :custom-style="{'color': '#00C3CE'}"
									:placeholderStyle="'color: #f000000;'" :clearable="false" :auto-height="true"
									:height="150" :maxlength="200" :placeholder="'请填写加油报账备注，最多输入200个字（选填）'" />
							</view>
						</view>
					</u-form-item>

					<u-form-item :border-bottom="false">
						<view class="i-row-textarea">
							<view class="r-title">报账凭证<label class="r-title-tip">（最多上传6张图片）</label></view>
							<view class="r-con">
								<u-upload ref="bzUf" width="200" height="200" max-count="6" :file-list="fm.uflist"
									:action="ufAction" :header="ufHeader" :name="'files'"
									:form-data="{ftype: fm.bzType.key+'_IMG', orderNum: fm.plateNum, uid: fm.uid}"
									:max-size="1024*1024*30"></u-upload>
							</view>
						</view>
					</u-form-item>
				</view>
			</view>
		</u-form>

		<u-toast ref="qtoast" />
	</view>
</template>

<script>
	import MySelect from '@/components/my-select/my-select.vue';
	import MyDateTime from '@/components/my-date-time/my-date-time.vue';

	export default {
		components: {
			MySelect,
			MyDateTime
		},
		data() {
			return {
				plateNum: '',
				// 维修详情输入框样式
				inpBtnStyl: {
					'color': '#00C3CE',
					'padding-right': '30rpx'
				},

				// 文件上传地址
				ufAction: this.C.upfileUrl,
				// 文件上传请求头信息
				ufHeader: {
					'token': uni.getStorageSync(this.C.uuid)
				},
				// 旧文件数据
				flist: [],

				// 表单对象
				fm: null,
				// 提交按钮
				sb: {
					load: false
				},

				// 加油方式列表
				jyWayList: [],
				// 加油站列表
				jyStationList: [],
			}
		},
		onLoad(e) {
			console.log('传入的参数', e);

			this.getUnRouteBzBaseData(e.id);

			
		},
		methods: {
			// 弹框列表选择
			mySeledMd(e) {
				this.fm[e.name] = e.obj;
			},
			// 选择日期时间
			setDateTime(e) {
				this.fm[e.name] = e.obj;
			},

			// 获取-非团上开支报账基本数据
			async getUnRouteBzBaseData(e) {
				const that = this,
					U = that.U;
				// 设置-加油方式
				let jyWays = [{
						id: 'XJ_JY',
						text: '现金加油',
					},
					{
						id: 'YP_JY',
						text: '油票加油',
					},
					{
						id: 'YGC_JY',
						text: '油罐车加油',
					},
					{
						id: 'CZK_JY',
						text: '充值卡加油',
					},
				]
				that.jyWayList = [];
				jyWays.forEach(it => {
					that.jyWayList.push({
						val: it.id,
						text: it.text
					});
				});
				let res = await that.$u.api.findComboCusList({
					cusTypeMark: 'OILSTATION',
					page: {
						pageNum: 1,
						pageSize: 999,
					}
				});
				if (res.code == 1) {

					// 设置-加油站列表

					that.jyStationList = [];
					res.data.forEach(it => {
						that.jyStationList.push({
							val: it.id,
							text: it.cusCompanySimpleName
						});
					});
					this.getBzDetail(e);

				}


			},
			// 获取-报账详情
			 getBzDetail(id) {
				const that = this;

				that.$u.api.getBzDetail({
					id: id
				}).then(res => {
					if (res.code == 1) {
						let jyWays = [{
								id: 'XJ_JY',
								text: '现金加油',
							},
							{
								id: 'YP_JY',
								text: '油票加油',
							},
							{
								id: 'YGC_JY',
								text: '油罐车加油',
							},
							{
								id: 'CZK_JY',
								text: '充值卡加油',
							},
						]
						let o = res.data;

						// 根据报账类型初始化对应数据
						let p = {};
						// 修改id
						p.id = o.id;
						// 报账车辆车牌
						that.plateNum = o.plateNum;
						p.plateNum = o.plateNum;
						// 报账类型
						p.bzType = 'JYJZ';
						// 车辆当前公里数
						p.currKm = o.currentKilo;
						// 加油方式
						if (o.oilWay) p.jyWay = {
							text: o.oilWay
						};
						for (let i = 0; i < jyWays.length; i++) {
							if (o.oilWay == jyWays[i].text) {
								p.jyWay.val = jyWays[i].id
							}
						}
						
					if (o.stationName) p.jyStation = {
						text: o.stationName,
						val:'',
					};
					console.log(o.stationName)
					console.log(p.jyStation.val)
					console.log(that.jyStationList)
					for (let i = 0; i < that.jyStationList.length; i++) {
						if (o.stationName == that.jyStationList[i].text) {
							p.jyStation.val = that.jyStationList[i].val
						}
					}
					console.log(p.jyStation,'p.jyStation')
						
						// 加油金额
						p.jyMoney = o.reimMoney;
						// 加油数量
						p.jyCount = o.oilRise == 0 ? '' : o.oilRise;
						// 加油日期
						p.jyDate = {
							date: that.datatime(o.payTime),
							time: ''
						};
						// 备注
						p.jyRemark = o.remark;
						// 图片id
						p.fids = [];
						// 默认图片数组
						let flist = [];
						if (o.reimVoucherUrl) {
							let fs = o.reimVoucherUrl.split(',');
							fs.forEach(it => {
								flist.push({

									url: 'https://cba360.com' + it
								});
							});
						}
						that.flist = flist; // 保存起来
						p.uflist = flist;

						that.fm = p;
						console.log('赋值', that.fm);
					}
				});
			},
			// 表单验证
			valFm() {
				const that = this,
					U = that.U,
					FV = that.FV;
				let fg = true,
					ps = U.scopy(that.fm),
					p = {};;

				p.jzType = ps.bzType.key;
				p.id = ps.id;
			p.moneyTypeId = 8;

				if (fg) {
					let plateNum = ps.plateNum;
					if (!plateNum) {
						fg = U.qinfo('请选择加油辆车');
					} else if (plateNum.length > 8) {
						fg = U.qinfo('车牌号格式错误');
					} else {
						p.plateNum = plateNum;
					}
				}

				if (fg) {
					let currKm = ps.currKm;
					if (!currKm || currKm < 1) {
						fg = U.qinfo('[加油车辆当前公里数]不能为空');
					} else {
						p.currentKilo = currKm;
					}
				}

				if (fg) {
					let jyWay = ps.jyWay.val;
					if (!jyWay) {
						fg = U.qinfo('[加油方式]不能为空');
					} else {
						p.oilWay = jyWay;
					}
				}
				if (fg) {
					let jyCount = ps.jyCount;
					if (!jyCount || jyCount == 0) {
						fg = U.qinfo('[加油数量]不能为空或0');
					} else if (!FV.isFloat(jyCount)) {
						fg = U.qinfo('[加油数量]格式错误');
					} else {
						p.oilRise = jyCount;
					}
				}

				if (fg) {
					let jyMoney = ps.jyMoney;
					if (!jyMoney || jyMoney == 0) {
						fg = U.qinfo('[加油金额]不能为空或0');
					} else if (!FV.isFloat(jyMoney)) {
						fg = U.qinfo('[加油金额]格式错误');
					} else {
						p.reimMoney = jyMoney;
					}
				}
				if (p.oilWay != 'XJ_JY') { // 油票加油
					if (fg) {
						let jyStation = ps.jyStation.val;
						if (!jyStation) {
							fg = U.qinfo('[加油站]不能为空');
						} else {
							p.stationId = jyStation;
						}
					}



					if (fg) {
						let jyMoney = ps.jyMoney;
						if (!jyMoney || jyMoney == 0) {
							fg = U.qinfo('[加油金额]不能为空或0');
						} else if (!FV.isFloat(jyMoney)) {
							fg = U.qinfo('[加油金额]格式错误');
						} else {
							p.reimMoney = jyMoney;
						}
					}
				} else { // 现金加油
					if (fg) {
						let jyMoney = ps.jyMoney;
						if (!jyMoney || jyMoney == 0) {
							fg = U.qinfo('[加油金额]不能为空或0');
						} else if (!FV.isFloat(jyMoney)) {
							fg = U.qinfo('[加油金额]格式错误');
						} else {
							p.reimMoney = jyMoney;
						}
					}
				}

				if (fg) {
					let jyDate = ps.jyDate.date;
					if (!jyDate) {
						//fg = U.qinfo('[加油日期]不能为空');
					} else if (U.str2date(jyDate + ' 00:00:00').getTime() > new Date().getTime()) {
						fg = U.qinfo('[加油日期]不能大于当前时间');
					} else {
						p.payTime = jyDate;
					}
				}

				if (fg) {
					let jyRemark = ps.jyRemark;
					if (jyRemark.length > 200) {
						fg = U.qinfo('[备注]最多填写200个字');
					} else {
						p.remark = jyRemark;
					}
				}

				if(fg){
					let uflist = that.$refs.bzUf.lists;
					if(uflist.length == 0){
						fg = U.qinfo('至少需要上传一张停车费小票图片');
					}else{
						let fids = [];
						uflist.forEach(it => {
							if(it.url && it.url.indexOf('_img') != -1){// 本地图片
								let is = that.flist.find(fit => it.url.indexOf(fit.url) != -1);
								let url = is.url.split('.com')[1]
								console.log(url,'url')
								fids.push(url);
							}else{// 新传图片
								if(it.response && it.response.data) fids.push(it.response.data.file.url);
							}
						});
						console.log(fids)
						if(fids.length == 0){
							fg = U.qinfo('上传图片'+uflist.length+'张，成功'+fids.length+'张');
						}else{
							p.reimVoucherUrl = fids.join(',');
						}
					}
				}

				return fg ? {
					staffReimInfo: [p]
				} : fg;
			},
			// 提交表单
			submitFm() {
				let that = this,
					ps = that.valFm(),
					U = that.U,
					sb = that.sb;
				
				if (ps != false) {
					ps.plateNum = that.plateNum
					console.log('提交参数', ps);
					sb.load = true;
					that.$u.api.adupAllUnRouteBz(ps).then((res) => {
						if (res.code != 1) {
							sb.load = false;
						} else {
							U.qtoast(that, {
								title: res.msg,
								type: 'success',
								duration: 1000,
								callback: function() {
									sb.load = false;

									// 刷新父级列表（刷新未报销的列表）
									uni.$emit('refJzList', 0);
									// 返回上一页
									uni.navigateBack({
										delta: 1
									});
								}
							});
						}
					}).catch(err => {
						sb.load = false;
					});
				}
			},
			datatime(e) {
				let originalDateTimeString = e;
				let date = new Date(originalDateTimeString);

				let year = date.getFullYear();
				let month = String(date.getMonth() + 1).padStart(2, '0');
				let day = String(date.getDate()).padStart(2, '0');
				let hours = String(date.getHours()).padStart(2, '0');
				let minutes = String(date.getMinutes()).padStart(2, '0');
				let seconds = String(date.getSeconds()).padStart(2, '0');

				let formattedDateTimeString = `${year}-${month}-${day}`;
				return formattedDateTimeString
			},

		}
	}
</script>

<style lang="scss">
	.adup-jybz {
		padding-top: 80rpx;
		padding-bottom: 10rpx;

		.f-item {
			margin: 10rpx !important;
		}
	}
</style>